import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutterlib/common/config/config.dart';
import 'package:flutterlib/common/utils/sp_utils.dart';
import 'package:flutterlib/common/style/quhui_style.dart';
import 'package:flutterlib/model/navigate/ActivityCity.dart';
import 'package:flutterlib/widgets/quhui_card_item.dart';
import 'package:flutterlib/widgets/bussiness/activity/sheet_indicator_widget.dart';

typedef void SelectItemChanged<int>(int tabIndex, int choiceIndex);

//选项框，点击后变换小箭头，弹出选择弹窗
class QuhuiSelectItemWidget extends StatefulWidget
    implements PreferredSizeWidget {
  final SelectItemChanged selectItemChanged;

  final RoundedRectangleBorder shape;

  final double elevation;

  final double height;

  final EdgeInsets margin;

  QuhuiSelectItemWidget(
    this.selectItemChanged, {
    this.elevation = 5.0,
    this.height = 70.0,
    this.shape,
    this.margin = const EdgeInsets.all(10.0),
  });

  @override
  _QuhuiSelectItemWidgetState createState() => _QuhuiSelectItemWidgetState();

  @override
  Size get preferredSize {
    return new Size.fromHeight(height);
  }
}

class _QuhuiSelectItemWidgetState extends State<QuhuiSelectItemWidget> {
  static const SHEET_TITLE = const ["类型", "城市", "举办者", "排序"];
  static const ONLINE_CONFIG = const ["全部", "线下", "线上"];
  static const OWNER_CONFIG = const ["全部", "个人", "机构"];
  static const ORDER_CONFIG = const ["默认", "按时间", "按距离"];
  List<ActivityCity> citys = [];
  Map<int, dynamic> choiceSelectMap = {};

  int selectIndex = -1;

  _QuhuiSelectItemWidgetState();

  @override
  void initState() {
    citys = getCitys();
    choiceSelectMap[0] = 0;
    choiceSelectMap[1] = 0;
    choiceSelectMap[2] = 0;
    choiceSelectMap[3] = 0;
  }

  List<ActivityCity> getCitys() {
    var citys = SpUtils.getString("citys");
    var cityStr = citys.isEmpty ?
        '''[{"key":"1","name":"城市"}]''' : citys;
    List<dynamic> decode = json.decode(cityStr);
    var list = decode.map((dynamic i) => ActivityCity.fromJson(i)).toList();
    return list;
  }

  _renderItem(String name, int index, Map<int, dynamic> map) {
    return new Expanded(
      child: RawMaterialButton(
          key: ValueKey(index == selectIndex),
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          constraints: const BoxConstraints(minWidth: 0.0, minHeight: 0.0),
          padding: EdgeInsets.all(5.0),
          child: Row(
            children: <Widget>[
              Text(
                getChoiceText(index, map[index]),
                style: QuhuiConstant.smallSubText,
              ),
              Image(
                width: 16,
                height: 16,
                image: index == selectIndex
                    ? AssetImage(Config.ASSETS_IMG + "play_square_up.png")
                    : AssetImage(Config.ASSETS_IMG + "play_square.png"),
              )
            ],
          ),
          onPressed: () {
            //修改小箭头方向
            setSelectState(index);
            //弹出底部选择框
            _showModalBottomSheet(context, index, map[index]);
          }),
    );
  }

  void setSelectState(int index) {
    setState(() {
      selectIndex = index;
    });
  }

  void setChoiceState(int index, int choiceIndex){
    setState(() {
      choiceSelectMap[index] = choiceIndex;
    });
  }

  _showModalBottomSheet(BuildContext context, int tabIndex, int selected) {
    var sheetTitle = SHEET_TITLE[tabIndex];
    Future<void> future = showModalBottomSheet(
      context: context,
      builder: (context) {
        var sheetIndicator = new SheetIndicatorWidget();
        return Stack(
          children: <Widget>[
            Container(
              height: 25,
              width: double.infinity,
              color: Colors.black54,
            ),
            Container(
              height: 644,
              width: double.infinity,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(25),
                  topRight: Radius.circular(25),
                ),
              ),
              child: Container(
                child: Column(
                  children: <Widget>[
                    sheetIndicator,
                    Container(
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.only(left: 24),
                      child: Text(
                        sheetTitle,
                        style: QuhuiConstant.largeTextBold,
                      ),
                    ),
                    Expanded(
                      child: GridView.count(
                          crossAxisCount: 4,
                          childAspectRatio: 1.8,
                          children: List.generate(
                            getChoiceLength(tabIndex),
                            (choiceindex) {
                              var gridItem = Container(
                                  alignment: Alignment.center,
                                  child: SizedBox(
                                    height: 32,
                                    width: 64,
                                    child: InkWell(
                                        customBorder:
                                            new RoundedRectangleBorder(
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(10.0)),
                                          side: BorderSide(
                                            color: Colors.black, //边线颜色为黄色
                                            width: 2, //边线宽度为2
                                          ),
                                        ),
                                        child: Container(
                                          alignment: Alignment.center,
                                          decoration: BoxDecoration(
                                              color: choiceindex == selected
                                                  ? QuhuiColors.mainThemeColor
                                                  : Colors.white,
                                              border: Border.all(
                                                  color: Color(0x14000000),
                                                  width: 1),
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(4))),
                                          child: Text(getChoiceText(
                                              tabIndex, choiceindex),
                                          style: QuhuiConstant.middleText,),
                                        ),
                                        onTap: () {
                                          widget.selectItemChanged(
                                              tabIndex, choiceindex);
                                          setChoiceState(tabIndex, choiceindex);
                                          print('tapped item ${tabIndex + 1}');
                                          Navigator.pop(context);
                                        }),
                                  ));
                              return gridItem;
                            },
                          )),
                    ),
                  ],
                ),
              ),
            ),
          ],
        );
      },
    );
    future.then((void value) => _closeModel(value));
  }

  void _closeModel(void value) {
    print("model close");
    setSelectState(-1);
  }

  _renderList() {
    List<Widget> list = new List();
    list.add(SizedBox(
      width: 16,
    ));
    for (int i = 0; i < 4; i++) {
      list.add(_renderItem(SHEET_TITLE[i], i, choiceSelectMap));
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return new QuhuiCardItem(
        elevation: widget.elevation,
        margin: widget.margin,
        color: QuhuiColors.mainBackgroundColor,
        shape: widget.shape ??
            new RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(4.0)),
            ),
        child: new Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: _renderList(),
        ));
  }

  int getChoiceLength(int tabIndex) {
    switch (tabIndex) {
      case 0:
        return ONLINE_CONFIG.length;
      case 1:
        return citys.length;
      case 2:
        return OWNER_CONFIG.length;
      case 3:
        return ORDER_CONFIG.length;
      default:
        return 0;
    }
  }

  getChoiceText(int tabIndex, int choiceIndex) {
    switch (tabIndex) {
      case 0:
        return ONLINE_CONFIG[choiceIndex];
      case 1:
        return citys[choiceIndex].name;
      case 2:
        return OWNER_CONFIG[choiceIndex];
      case 3:
        return ORDER_CONFIG[choiceIndex];
      default:
        return "";
    }
  }
}
